/*

log2mongo :: Logs messages to MongoDB
__________________________________________

Copyright (c) 2011 Gaurav Kumar, Pivotal Security LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/


/*
 *               COMPILING & LINKING :
 *
 * g++ tcplogger.cpp -I/path/to/mongoDBC/mongoC++Driver/util/net/ -I/path/to/simpleini -I/path/to/mongoDBC/mongoC++Driver/mongo -lboost_system -lpthread -Wall -lmongoclient -o tcplogger
 *
*/


#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include "client/dbclient.h"
#include "bson/oid.h"
#include "SimpleIni.h"
#include "hostandport.h"



using boost::asio::ip::tcp;
using namespace std;
using namespace mongo;

////////////////////////////    SESSION CLASS  ///////////////////////////////////////


class session
{
public:
  session(boost::asio::io_service& io_service,mongo::DBClientConnection* conn,int nb,string filterStringValue)
    : socket_(io_service)
  {
	  mConn=conn;
	  numbytes=nb;
	  filterString=filterStringValue;

  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start(mongo::DBClientConnection* mConn)
  {
	  async_read(socket_, boost::asio::buffer(data_),
	          bind(&session::handle_read, this,boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
  }

private:
  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
    if (!error)
    {

    	 std::string data(data_,bytes_transferred);
    	 str=str.append(data);
    	 size_t f= str.find("\n");

    	 if (f!=string::npos){ // newline has been found, this means we have the log available to be sent to DB

    	 istringstream fil (filterString,istringstream::in);

    	 // if no filter strings have been found, just send all the logs to DB
    	 if(filterString.empty()==true){

 	 	         	   SendToDB(str,mConn);
 	 	         	   str.clear();

 	 	        }
				// else, parse the filter string line by line and for each line check if fist numbytes match content
				 else

 	 	        {
					std::istringstream f(filterString);
					    std::string line;
					    while (std::getline(f, line)) {
					         tmpLine=str.substr(0,numbytes);
					         if(tmpLine.find(line)!=string::npos){

					        	   SendToDB(str,mConn);
					        	   str.clear();
					         }
					    }
					    str.clear();
 	 	        }
    	 }

    	 async_read(socket_, boost::asio::buffer(data_),
    	 	          bind(&session::handle_read, this,boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
    }
    else
    {
    	delete this;
    }
}


void SendToDB(string str,mongo::DBClientConnection* mConn ){

	  BSONObjBuilder b;
	  b.append("logString", str);
	  BSONObj p = b.obj();
	  try{
        	 mConn->insert("inbox.Logs",p);
		  } catch (std::exception& e)
	 	  {
	 	  std::cerr << "Exception occurred while inserting log: " << e.what() << "\n";
 	   }


  }

  tcp::socket socket_;
  enum { max_length = 1 }; // we are reading 1 byte at a time to solve the challenge of "buffering" -- if we don't do this, this has caused log to be "spilt" before.
  char data_[max_length]; // this stores the data we have received
  int numbytes; // this is used to check content for first numbytes used in filtering
  string filterString;
  string str;
  string tmpLine;
  string tmpLine2;
  size_t found;
  mongo::DBClientConnection* mConn; // connection pointer to DB
};

////////////////////////////    SERVER CLASS  ///////////////////////////////////////

class server
{

public:
  server(boost::asio::io_service& io_service, short port,const char * dbhost, int nb,std::string content): io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
  {

	  numBytes=nb;
	  filterString=content;
	  start_accept(dbhost,numBytes,filterString);
  }

private:
  void start_accept(const char * dbhostinfo,int nb,string filterString)
  {

	  dbhost=dbhostinfo;
	  hp=string(dbhost);

	  try{
	         using namespace mongo;
	           mConn = new mongo::DBClientConnection(true,NULL,NULL ); // first parameter has been set to true to make sure we re-connect to DB when DB comes back online
	           mConn->connect(hp);

	           //if(mConn->auth("db","user","pass",err,false)){  } //TODO: implement DB authenication
	           }
	       catch( DBException &e ) {
	       cout << "Exception while creating DB Connection object: " << e.what() << endl;
		}


    session* new_session = new session(io_service_ ,mConn,numBytes,filterString);
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

  void handle_accept(session* new_session,
      const boost::system::error_code& error)
  {
    if (!error)
    {
      new_session->start(mConn);
    }
    else
    {
      delete new_session;
    }

    start_accept(dbhost,numBytes,filterString);
  }
private:
  boost::asio::io_service& io_service_;
  tcp::acceptor acceptor_;
  const char * dbhost;
  mongo::DBClientConnection* mConn;
  HostAndPort hp;
  int numBytes;
  string filterString;
};
extern "C"


////////////////////////////    MAIN()  ///////////////////////////////////////


int main(int argc, char* argv[])
{

using namespace std;
using namespace mongo;

 try
  {
    cout<<"*************************************************************************************\n";
    cout<<"log2mongo :: Logs messages to MongoDB"<<endl;
	cout<<"Version 0.1"<<endl;
	cout<<"Copyright (c) 2011 Gaurav Kumar, Pivotal Security LLC"<<endl;
	cout<<endl;
	cout<<"Usage: ./log2mongo"<<endl;
	cout<<"config.ini file must be in same directory from where you are running ./logger"<<endl;
	cout<<endl;
	cout<<endl;
	cout<<"*************************************************************************************\n";


	CSimpleIniCaseA  ini;
	CSimpleIniCaseA::TNamesDepend values;
    ini.SetUnicode();
    ini.SetMultiKey();
    SI_Error rc;
    std::stringstream LogOnly_string;


    // read config file
    rc= ini.LoadFile("config.ini");
    if(rc<0){std::cerr<<"!!!  config.ini not found in current directory. Proceeding with defaults.   !!!"<<endl<<endl;;
    } else {
    	cout<<"config.ini has been read"<<endl<<endl;
    }


    // user friendly info-

    const char * pValtcp = ini.GetValue("logger", "TCPport", "10514");
    const char * dbhost = ini.GetValue("db", "host:port", "localhost:27017");
    const char * numBytes = ini.GetValue("logger", "LogOnly_firstNbytes", "114");
    //ini.GetAllValues(L"", L"LogOnly_string", values);
    ini.GetAllValues("logger", "LogOnly_string", values);
    cout<<"Going to look in first "<<numBytes<<" bytes for following strings: "<<endl;
    CSimpleIniCaseA::TNamesDepend::const_iterator i;

    // get filtering string from config file

    for (i = values.begin(); i != values.end(); ++i)
    	LogOnly_string << i->pItem <<"\n";
    if(LogOnly_string.str().empty()!=true){
    cout<<LogOnly_string.str()<<endl;}
    else{
    	cout<<"No filter strings found! Going to send all logs received\n";
    }

    cout<<"Going to listen on TCP port "<<pValtcp<<endl;
    cout<<"Going to use MongoDB instance running on "<<dbhost<<endl;


    boost::asio::io_service tcp_service;
    server tcp(tcp_service, atoi(pValtcp),dbhost,atoi(numBytes),LogOnly_string.str());
    cout<<"Now ready to accept messages..."<<endl;
    tcp_service.run();


  }
  catch (std::exception& e)
  {
    std::cerr << "Exception found: " << e.what() << "\n";
  }

  return 0;
}
